﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Web;
using System.Text.RegularExpressions;
using System.IO;
using System.Net;
using System.Reflection;
using System.Threading;
using System.Web.Script.Serialization;

namespace AliCMS.CourseModule.Bll
{
    public partial class MemberOrder : DbObjectBase, IMemberOrder
	{
		public MemberOrder(int instanceID, string lang, bool checkRight, string database)
			: base(instanceID, lang, checkRight, database)
		{
		}

		public override object ExecuteService(HttpContext context)
		{
			object result = null;

			string operation = context.Request.QueryString["Operation"];
			if (operation == "Add")
			{
				Dictionary<string, object> item = new Dictionary<string, object>();
				string value = null;
				value = context.Request.Form["LevelID"];
				if (value != null) item[Alias.MemberOrder.LevelID] = value;
				value = context.Request.Form["TimeUnit"];
				if (value != null) item[Alias.MemberOrder.TimeUnit] = value;
				value = context.Request.Form["TimeAmount"];
				if (value != null) item[Alias.MemberOrder.TimeAmount] = value;
				value = context.Request.Form["UserID"];
				if (value != null) item[Alias.MemberOrder.UserID] = value;
				value = context.Request.Form["UserName"];
				if (value != null) item[Alias.MemberOrder.UserName] = value;
                value = context.Request.Form["UserNickname"];
                if (value != null) item[Alias.MemberOrder.UserNickname] = value;
                value = context.Request.Form["UserHead"];
                if (value != null) item[Alias.MemberOrder.UserHead] = value;
                value = context.Request.Form["DistributerID"];
				if (value != null) item[Alias.MemberOrder.DistributerID] = value;
				value = context.Request.Form["DistributerName"];
				if (value != null) item[Alias.MemberOrder.DistributerName] = value;
                value = context.Request.Form["DistributerNickname"];
                if (value != null) item[Alias.MemberOrder.DistributerNickname] = value;
                value = context.Request.Form["DistributerHead"];
                if (value != null) item[Alias.MemberOrder.DistributerHead] = value;
                value = context.Request.Form["DistributerIsAgent"];
				if (value != null) item[Alias.MemberOrder.DistributerIsAgent] = value;
				value = context.Request.Form["AgentCommision"];
				if (value != null) item[Alias.MemberOrder.AgentCommision] = value;
				value = context.Request.Form["Price"];
				if (value != null) item[Alias.MemberOrder.Price] = value;
				value = context.Request.Form["Sum"];
				if (value != null) item[Alias.MemberOrder.Sum] = value;
				value = context.Request.Form["PaymentID"];
				if (value != null) item[Alias.MemberOrder.PaymentID] = value;
				value = context.Request.Form["PaymentName"];
				if (value != null) item[Alias.MemberOrder.PaymentName] = value;
				value = context.Request.Form["PaymentType"];
				if (value != null) item[Alias.MemberOrder.PaymentType] = value;
				value = context.Request.Form["PaymentAccountName"];
				if (value != null) item[Alias.MemberOrder.PaymentAccountName] = value;
				value = context.Request.Form["PaymentAccountNo"];
				if (value != null) item[Alias.MemberOrder.PaymentAccountNo] = value;

				result = Add(item);
			}
			else if (operation == "Modify")
			{
				int id = Convert.ToInt32(context.Request.QueryString["ID"]);

				Dictionary<string, object> changes = new Dictionary<string, object>();
				string value = null;
                value = context.Request.Form["LevelID"];
                if (value != null) changes[Alias.MemberOrder.LevelID] = value;
                value = context.Request.Form["PaymentID"];
				if (value != null) changes[Alias.MemberOrder.PaymentID] = value;
				value = context.Request.Form["PaymentName"];
				if (value != null) changes[Alias.MemberOrder.PaymentName] = value;
				value = context.Request.Form["PaymentType"];
				if (value != null) changes[Alias.MemberOrder.PaymentType] = value;
				value = context.Request.Form["PaymentAccountName"];
				if (value != null) changes[Alias.MemberOrder.PaymentAccountName] = value;
				value = context.Request.Form["PaymentAccountNo"];
				if (value != null) changes[Alias.MemberOrder.PaymentAccountNo] = value;

				Modify(id, changes);
			}
			else if (operation == "Delete")
			{
				string id = context.Request.QueryString["ID"];

				string[] ids = id.Split('|');
				for (int i = 0; i < ids.Length; i++)
				{
					if (String.IsNullOrEmpty(ids[i]))
						continue;

					Delete(Convert.ToInt32(ids[i]));
				}
			}
			else if (operation == "List")
			{
				string value = null;

				int page = -1;
				value = context.Request.QueryString["Page"];
				if (value != null) page = Convert.ToInt32(value);

				int pageSize = -1;
				value = context.Request.QueryString["PageSize"];
				if (value != null) pageSize = Convert.ToInt32(value);

				string condition = context.Request.QueryString["Condition"];
				string sort = context.Request.QueryString["Sort"];

				result = List(page, pageSize, condition, sort);
			}
			else if (operation == "Pay")
			{
				int id = Convert.ToInt32(context.Request.QueryString["ID"]);

				Dictionary<string, object> data = new Dictionary<string, object>();
				string value = null;

				//Amount
				/*
				value = context.Request.Form["Amount"];
				if (value != null && !String.IsNullOrEmpty(value))
					data["Amount"] = Convert.ToDecimal(value);
				*/

				//PayTime
				value = context.Request.Form["PayTime"];
				if (value != null && !String.IsNullOrEmpty(value))
					data["PayTime"] = Convert.ToDateTime(value);
				else
					data["PayTime"] = DateTime.Now;

				//PayMemo
				value = context.Request.Form["PayMemo"];
				if (value != null)
					data["PayMemo"] = value;
				else
					data["PayMemo"] = DBNull.Value;

				//PaymentID
				value = context.Request.Form["PaymentID"];
				if (!String.IsNullOrEmpty(value))
					data["PaymentID"] = new Guid(value);
				else
					data["PaymentID"] = DBNull.Value;

				//PaymentName
				value = context.Request.Form["PaymentName"];
				if (value != null)
					data["PaymentName"] = value;
				else
					data["PaymentName"] = DBNull.Value;

				//PaymentType
				value = context.Request.Form["PaymentType"];
				if (value != null)
					data["PaymentType"] = value;
				else
					data["PaymentType"] = DBNull.Value;

				//PaymentAccountName
				value = context.Request.Form["PaymentAccountName"];
				if (value != null)
					data["PaymentAccountName"] = value;
				else
					data["PaymentAccountName"] = DBNull.Value;

				//PaymentAccount
				value = context.Request.Form["PaymentAccountNo"];
				if (value != null)
					data["PaymentAccountNo"] = value;
				else
					data["PaymentAccountNo"] = DBNull.Value;

				//从app调用时，发来的当前用户ID
				data["CurUserID"] = context.Request.Form["CurUserID"];
				data["CurUserName"] = context.Request.Form["CurUserName"];

				//
				Pay(id, data);
			}
			else if (operation == "Refund")
			{
				int id = Convert.ToInt32(context.Request.QueryString["ID"]);

				Dictionary<string, object> data = new Dictionary<string, object>();
				string value = null;

				//Amount
				value = context.Request.Form["Amount"];
				if (!String.IsNullOrEmpty(value))
					data["Amount"] = Convert.ToDecimal(value);

				//RefundTime
				value = context.Request.Form["RefundTime"];
				if (!String.IsNullOrEmpty(value))
					data["RefundTime"] = Convert.ToDateTime(value);
				else
					data["RefundTime"] = DateTime.Now;

				//RefundMemo
				value = context.Request.Form["RefundMemo"];
				if (value != null)
					data["RefundMemo"] = value;
				else
					data["RefundMemo"] = DBNull.Value;

				//从app调用时，发来的当前用户ID
				data["CurUserID"] = context.Request.Form["CurUserID"];
				data["CurUserName"] = context.Request.Form["CurUserName"];

				Refund(id, data);
			}
			else if (operation == "Deliver")
			{
				int id = Convert.ToInt32(context.Request.QueryString["ID"]);

				Dictionary<string, object> data = new Dictionary<string, object>();
				string value = null;
				value = context.Request.Form["DeliverTime"];
				if (value != null)
					data[Alias.MemberOrder.DeliverTime] = Convert.ToDateTime(value);
				else
					data[Alias.MemberOrder.DeliverTime] = DateTime.Now;
				value = context.Request.Form["DeliverMemo"];
				if (value != null) data[Alias.MemberOrder.DeliverMemo] = value;

				//从app调用时，发来的当前用户ID
				data["CurUserID"] = context.Request.Form["CurUserID"];
				data["CurUserName"] = context.Request.Form["CurUserName"];

				Deliver(id, data);
			}
			else if (operation == "Return")
			{
				int id = Convert.ToInt32(context.Request.QueryString["ID"]);

				Dictionary<string, object> data = new Dictionary<string, object>();
				string value = null;
				value = context.Request.Form["ReturnTime"];
				if (value != null)
					data[Alias.MemberOrder.ReturnTime] = Convert.ToDateTime(value);
				else
					data[Alias.MemberOrder.ReturnTime] = DateTime.Now;
				value = context.Request.Form["ReturnMemo"];
				if (value != null)
					data[Alias.MemberOrder.ReturnMemo] = value;
				else
					data[Alias.MemberOrder.ReturnMemo] = DBNull.Value;

				//从app调用时，发来的当前用户ID
				data["CurUserID"] = context.Request.Form["CurUserID"];
				data["CurUserName"] = context.Request.Form["CurUserName"];

				Return(id, data);
			}
			else if (operation == "Finish")
			{
				string id = context.Request.QueryString["ID"];

				string[] ids = id.Split('|');
				for (int i = 0; i < ids.Length; i++)
				{
					if (String.IsNullOrEmpty(ids[i]))
						continue;

					Finish(Convert.ToInt32(ids[i]));
				}
			}
			else if (operation == "Cancel")
			{
				string id = context.Request.QueryString["ID"];

				string[] ids = id.Split('|');
				for (int i = 0; i < ids.Length; i++)
				{
					if (String.IsNullOrEmpty(ids[i]))
						continue;

					Cancel(Convert.ToInt32(ids[i]));
				}
			}
			else if (operation == "Archive")
			{
				string id = context.Request.QueryString["ID"];

				string[] ids = id.Split('|');
				for (int i = 0; i < ids.Length; i++)
				{
					if (String.IsNullOrEmpty(ids[i]))
						continue;

					Archive(Convert.ToInt32(ids[i]));
				}
			}
			else if (operation == "Get")
			{
				object id = null;
				if (Regex.IsMatch(context.Request.QueryString["ID"], @"^\d+$"))
					id = Convert.ToInt32(context.Request.QueryString["ID"]);
				else
					id = new Guid(context.Request.QueryString["ID"]);
				result = Get(id);
			}
			else if (operation == "OnlinePayRequest")
			{
                result = OnlinePayRequest(new Guid(context.Request.QueryString["ID"]));
            }
            else if (operation == "OnlinePayNotify")
			{
                result = OnlinePayNotify();
			}
            #region 统计
            else if (operation == "Stat")
            {
                Dictionary<string, object> data = new Dictionary<string, object>();
                string value = null;
                value = context.Request.QueryString["Start"];
                if (value != null) data["Start"] = value;
                value = context.Request.QueryString["End"];
                if (value != null) data["End"] = value;
                value = context.Request.QueryString["IsFinished"];
                if (value != null) data["IsFinished"] = value;
                value = context.Request.QueryString["IsArchived"];
                if (value != null) data["IsArchived"] = value;
                value = context.Request.QueryString["IsCanceled"];
                if (value != null) data["IsCanceled"] = value;
                value = context.Request.QueryString["IsPayed"];
                if (value != null) data["IsPayed"] = value;
                value = context.Request.QueryString["IsDelivered"];
                if (value != null) data["IsDelivered"] = value;

                result = Stat(data);
            }
            else if (operation == "StatHourly")
            {
                Dictionary<string, object> data = new Dictionary<string, object>();
                string value = null;
                value = context.Request.QueryString["Start"];
                if (value != null) data["Start"] = value;
                value = context.Request.QueryString["End"];
                if (value != null) data["End"] = value;
                value = context.Request.QueryString["IsFinished"];
                if (value != null) data["IsFinished"] = value;
                value = context.Request.QueryString["IsArchived"];
                if (value != null) data["IsArchived"] = value;
                value = context.Request.QueryString["IsCanceled"];
                if (value != null) data["IsCanceled"] = value;
                value = context.Request.QueryString["IsPayed"];
                if (value != null) data["IsPayed"] = value;
                value = context.Request.QueryString["IsDelivered"];
                if (value != null) data["IsDelivered"] = value;

                result = StatHourly(data);
            }
            else if (operation == "StatDaily")
            {
                Dictionary<string, object> data = new Dictionary<string, object>();
                string value = null;
                value = context.Request.QueryString["Start"];
                if (value != null) data["Start"] = value;
                value = context.Request.QueryString["End"];
                if (value != null) data["End"] = value;
                value = context.Request.QueryString["IsFinished"];
                if (value != null) data["IsFinished"] = value;
                value = context.Request.QueryString["IsArchived"];
                if (value != null) data["IsArchived"] = value;
                value = context.Request.QueryString["IsCanceled"];
                if (value != null) data["IsCanceled"] = value;
                value = context.Request.QueryString["IsPayed"];
                if (value != null) data["IsPayed"] = value;
                value = context.Request.QueryString["IsDelivered"];
                if (value != null) data["IsDelivered"] = value;

                result = StatDaily(data);
            }
            else if (operation == "StatMonthly")
            {
                Dictionary<string, object> data = new Dictionary<string, object>();
                string value = null;
                value = context.Request.QueryString["Start"];
                if (value != null) data["Start"] = value;
                value = context.Request.QueryString["End"];
                if (value != null) data["End"] = value;
                value = context.Request.QueryString["IsFinished"];
                if (value != null) data["IsFinished"] = value;
                value = context.Request.QueryString["IsArchived"];
                if (value != null) data["IsArchived"] = value;
                value = context.Request.QueryString["IsCanceled"];
                if (value != null) data["IsCanceled"] = value;
                value = context.Request.QueryString["IsPayed"];
                if (value != null) data["IsPayed"] = value;
                value = context.Request.QueryString["IsDelivered"];
                if (value != null) data["IsDelivered"] = value;

                result = StatMonthly(data);
            }
            #endregion
            #region 代理统计
            else if (operation == "Agent_StatOne")
            {
                Dictionary<string, object> data = new Dictionary<string, object>();
                string value = null;
                value = context.Request.QueryString["Start"];
                if (value != null) data["Start"] = value;
                value = context.Request.QueryString["End"];
                if (value != null) data["End"] = value;
                value = context.Request.QueryString["IsFinished"];
                if (value != null) data["IsFinished"] = value;
                value = context.Request.QueryString["IsArchived"];
                if (value != null) data["IsArchived"] = value;
                value = context.Request.QueryString["IsCanceled"];
                if (value != null) data["IsCanceled"] = value;
                value = context.Request.QueryString["IsPayed"];
                if (value != null) data["IsPayed"] = value;
                value = context.Request.QueryString["IsDelivered"];
                if (value != null) data["IsDelivered"] = value;
                value = context.Request.QueryString["Depth"];
                if (value != null) data["Depth"] = value;

                result = Agent_StatOne(new Guid(context.Request.QueryString["AgentID"]), data);
            }
            else if (operation == "Agent_StatAll")
            {
                Dictionary<string, object> data = new Dictionary<string, object>();
                string value = null;
                value = context.Request.QueryString["Start"];
                if (value != null) data["Start"] = value;
                value = context.Request.QueryString["End"];
                if (value != null) data["End"] = value;
                value = context.Request.QueryString["IsFinished"];
                if (value != null) data["IsFinished"] = value;
                value = context.Request.QueryString["IsArchived"];
                if (value != null) data["IsArchived"] = value;
                value = context.Request.QueryString["IsCanceled"];
                if (value != null) data["IsCanceled"] = value;
                value = context.Request.QueryString["IsPayed"];
                if (value != null) data["IsPayed"] = value;
                value = context.Request.QueryString["IsDelivered"];
                if (value != null) data["IsDelivered"] = value;
                value = context.Request.QueryString["Depth"];
                if (value != null) data["Depth"] = value;

                result = Agent_StatAll(data);
            }
            else if (operation == "Agent_StatHourly")
            {
                Dictionary<string, object> data = new Dictionary<string, object>();
                string value = null;
                value = context.Request.QueryString["Start"];
                if (value != null) data["Start"] = value;
                value = context.Request.QueryString["End"];
                if (value != null) data["End"] = value;
                value = context.Request.QueryString["IsFinished"];
                if (value != null) data["IsFinished"] = value;
                value = context.Request.QueryString["IsArchived"];
                if (value != null) data["IsArchived"] = value;
                value = context.Request.QueryString["IsCanceled"];
                if (value != null) data["IsCanceled"] = value;
                value = context.Request.QueryString["IsPayed"];
                if (value != null) data["IsPayed"] = value;
                value = context.Request.QueryString["IsDelivered"];
                if (value != null) data["IsDelivered"] = value;
                value = context.Request.QueryString["Depth"];
                if (value != null) data["Depth"] = value;

                result = Agent_StatHourly(new Guid(context.Request.QueryString["AgentID"]), data);
            }
            else if (operation == "Agent_StatDaily")
            {
                Dictionary<string, object> data = new Dictionary<string, object>();
                string value = null;
                value = context.Request.QueryString["Start"];
                if (value != null) data["Start"] = value;
                value = context.Request.QueryString["End"];
                if (value != null) data["End"] = value;
                value = context.Request.QueryString["IsFinished"];
                if (value != null) data["IsFinished"] = value;
                value = context.Request.QueryString["IsArchived"];
                if (value != null) data["IsArchived"] = value;
                value = context.Request.QueryString["IsCanceled"];
                if (value != null) data["IsCanceled"] = value;
                value = context.Request.QueryString["IsPayed"];
                if (value != null) data["IsPayed"] = value;
                value = context.Request.QueryString["IsDelivered"];
                if (value != null) data["IsDelivered"] = value;
                value = context.Request.QueryString["Depth"];
                if (value != null) data["Depth"] = value;

                result = Agent_StatDaily(new Guid(context.Request.QueryString["AgentID"]), data);
            }
            else if (operation == "Agent_StatMonthly")
            {
                Dictionary<string, object> data = new Dictionary<string, object>();
                string value = null;
                value = context.Request.QueryString["Start"];
                if (value != null) data["Start"] = value;
                value = context.Request.QueryString["End"];
                if (value != null) data["End"] = value;
                value = context.Request.QueryString["IsFinished"];
                if (value != null) data["IsFinished"] = value;
                value = context.Request.QueryString["IsArchived"];
                if (value != null) data["IsArchived"] = value;
                value = context.Request.QueryString["IsCanceled"];
                if (value != null) data["IsCanceled"] = value;
                value = context.Request.QueryString["IsPayed"];
                if (value != null) data["IsPayed"] = value;
                value = context.Request.QueryString["IsDelivered"];
                if (value != null) data["IsDelivered"] = value;
                value = context.Request.QueryString["Depth"];
                if (value != null) data["Depth"] = value;

                result = Agent_StatMonthly(new Guid(context.Request.QueryString["AgentID"]), data);
            }
            #endregion
            else
            {
				throw new Exception("lang_header_param");
			}

            if (_result != null)
                return _result;
            else
                return result;
        }

        public int GetInnerIDFromGuid(Guid guid)
		{
			return Dal.GetInnerIDFromGuid(guid);
		}
		public Guid GetGuidFromInnerID(object id)
		{
			return Dal.GetGuidFromInnerID(id);
		}
		public Dictionary<string, object> Get(object id)
		{
			if (CheckRight)
			{
				Guid guid;
				if (id is Guid)
					guid = (Guid)id;
				else
					guid = Dal.GetGuidFromInnerID(id);
				ValidateRight("Get", guid);
			}

			return Dal.Get(id);
		}
		public Guid Add(Dictionary<string, object> item)
		{
			if (CheckRight)
			{
				ValidateRight("Add", Guid.Empty);
			}

			if (!item.ContainsKey(Alias.MemberOrder.ID) || item[Alias.MemberOrder.ID].ToString() == String.Empty)
				item[Alias.MemberOrder.ID] = Guid.NewGuid();
			else if (!(item[Alias.MemberOrder.ID] is Guid))
				item[Alias.MemberOrder.ID] = new Guid(item[Alias.MemberOrder.ID].ToString());

			if (item.ContainsKey(Alias.MemberOrder.LevelID))
			{
				string levelId = item[Alias.MemberOrder.LevelID].ToString();
				if (levelId == String.Empty || levelId == Guid.Empty.ToString())
					item[Alias.MemberOrder.LevelID] = DBNull.Value;
				else
					item[Alias.MemberOrder.LevelID] = new Guid(levelId);
			}

			if (item.ContainsKey(Alias.MemberOrder.UserID))
			{
				string userId = item[Alias.MemberOrder.UserID].ToString();
				if (userId == String.Empty || userId == Guid.Empty.ToString())
					item[Alias.MemberOrder.UserID] = DBNull.Value;
				else
					item[Alias.MemberOrder.UserID] = new Guid(userId);
			}

			if (item.ContainsKey(Alias.MemberOrder.DistributerID))
			{
				string distributerId = item[Alias.MemberOrder.DistributerID].ToString();
				if (distributerId == String.Empty || distributerId == Guid.Empty.ToString())
					item[Alias.MemberOrder.DistributerID] = DBNull.Value;
				else
					item[Alias.MemberOrder.DistributerID] = new Guid(distributerId);
			}

			if (item.ContainsKey(Alias.MemberOrder.PaymentID))
			{
				string paymentId = item[Alias.MemberOrder.PaymentID].ToString();
				if (paymentId == String.Empty || paymentId == Guid.Empty.ToString())
					item[Alias.MemberOrder.PaymentID] = DBNull.Value;
				else
					item[Alias.MemberOrder.PaymentID] = new Guid(paymentId);
			}

			//创建人
			Dictionary<string, string> user = Manager.User;
			item[Alias.MemberOrder.CreatorName] = user["Name"];
			item[Alias.MemberOrder.CreatorID] = new Guid(user["ID"]);

			Dal.Add(item);

            return (Guid)item[Alias.MemberOrder.ID];
		}
		public void Modify(int id, Dictionary<string, object> changes)
		{
            Dictionary<string, object> member = Dal.Get(id);
            if (CheckRight)
			{
                //Guid guid = Dal.GetGuidFromInnerID(id);
                ValidateRight("Modify", (Guid)member[Alias.MemberOrder.ID]);
            }

            if (changes.ContainsKey(Alias.MemberOrder.PaymentID))
			{
				string paymentId = changes[Alias.MemberOrder.PaymentID].ToString();
				if (paymentId == String.Empty || paymentId == Guid.Empty.ToString())
					changes[Alias.MemberOrder.PaymentID] = DBNull.Value;
				else
					changes[Alias.MemberOrder.PaymentID] = new Guid(paymentId);
			}

            #region 如果修改代理编号，判断是否已经被别人使用
            /*
            if (changes.ContainsKey(Alias.MemberOrder.No))
            {
                if (changes[Alias.MemberOrder.No].ToString() == member[Alias.MemberOrder.No].ToString())
                {
                    changes.Remove(Alias.MemberOrder.No);
                }
                else
                {
                    DataTable table = Dal.List(1, 1, Alias.MemberOrder.SubInstanceID + "=" + member[Alias.MemberOrder.SubInstanceID] + " and " + Alias.MemberOrder.No + "=" + changes[Alias.MemberOrder.No], null);
                    if (table.Rows.Count > 0)//该代理编号已被别人使用
                    {
                        _result = "{\"error\":1,\"result\":\"该会员编号已被别人使用!\"}";
                        return;
                    }
                }
            }
            */
            #endregion

            if (changes.ContainsKey(Alias.MemberOrder.LevelID))
            {
                if (changes[Alias.MemberOrder.LevelID].ToString() == member[Alias.MemberOrder.LevelID].ToString())
                    changes.Remove(Alias.MemberOrder.LevelID);
                else
                    changes[Alias.MemberOrder.LevelID] = new Guid(changes[Alias.MemberOrder.LevelID].ToString());
            }

            if (changes.Count > 0)
                Dal.Modify(id, changes);

            #region 联系人信息修改【屏蔽企业模块的代码】
            /*
            HttpRequest req = HttpContext.Current.Request;
            if (!String.IsNullOrEmpty(req.Form["Name"]))
            {
                DataRow[] rows = Manager.Instances.Select(SystemModule.Alias.Module.Namespace + "='AliCMS.CompanyModule'");
                using (IDbObject bll = (IDbObject)Manager.CreateObject("Contact", Convert.ToInt32(rows[0][SystemModule.Alias.Instance.InnerID]), Lang, false))
                {
                    DataTable table = bll.List(1, 1, CompanyModule.Alias.Contact.UserID + "=" + member[Alias.MemberOrder.UserID], null);

                    if (table.Rows.Count > 0)
                    {
                        changes.Clear();
                        changes[CompanyModule.Alias.Contact.Name] = req.Form["Name"];
                        changes[CompanyModule.Alias.Contact.Mobile] = req.Form["Mobile"];
                        changes[CompanyModule.Alias.Contact.Wechat] = req.Form["Wechat"];
                        changes[CompanyModule.Alias.Contact.Head] = req.Form["Head"];
                        bll.Modify(Convert.ToInt32(table.Rows[0][CompanyModule.Alias.Contact.InnerID]), changes);
                    }
                }
            }
            */
            #endregion

            _result = "{\"error\":0}";
        }
        public void Delete(int id)
		{
			if (CheckRight)
			{
				Guid guid = Dal.GetGuidFromInnerID(id);
				ValidateRight("Delete", guid);
			}

			Dal.Delete(id);
		}
		public DataTable List(int page, int pageSize, string condition, string sort)
		{
			if (CheckRight)
			{
				ValidateRight("List", Guid.Empty);
			}

			return Dal.List(page, pageSize, condition, sort);
		}
		public int GetRecordCount(string condition)
		{
			return Dal.GetRecordCount(condition);
		}

		public void Pay(int id, Dictionary<string, object> data)
		{
            Dictionary<string, object> order = Dal.Get(id);
            if (CheckRight)
            {
                //Guid guid = Dal.GetGuidFromInnerID(id);
                ValidateRight("Pay", (Guid)order[Alias.MemberOrder.ID]);
            }

            #region 权限
            String curUserId = Convert.ToString(data["CurUserID"]);
            String curUserName = Convert.ToString(data["CurUserName"]);
            if (String.IsNullOrEmpty(curUserId))
            {
                Dictionary<string, string> user = Manager.User;
                if (user == null)
                {
                    Exception exp = new Exception("lang_no_right");
                    throw exp;
                }
                curUserId = user["ID"];
                curUserName = user["Name"];
            }
            #endregion

			#region 设置状态
			Dictionary<string, object> changes = new Dictionary<string, object>();
			changes[Alias.MemberOrder.PayTime] = data["PayTime"];
			changes[Alias.MemberOrder.PayMemo] = data["PayMemo"];
			changes[Alias.MemberOrder.PaymentID] = data["PaymentID"];
			changes[Alias.MemberOrder.PaymentName] = data["PaymentName"];
			changes[Alias.MemberOrder.PaymentType] = data["PaymentType"];
			changes[Alias.MemberOrder.PaymentAccountName] = data["PaymentAccountName"];
			changes[Alias.MemberOrder.PaymentAccountNo] = data["PaymentAccountNo"];
			changes[Alias.MemberOrder.PayOperatorID] = new Guid(curUserId);
			changes[Alias.MemberOrder.PayOperatorName] = curUserName;
			changes[Alias.MemberOrder.IsPayed] = 2;

			Dal.Modify(id, changes);
            #endregion

            //支付后处理
            OnAfterPay(order);
        }
        public void Refund(int id, Dictionary<string, object> data)
		{
            Dictionary<string, object> order = Dal.Get(id);
            if (CheckRight)
            {
                ValidateRight("Refund", (Guid)order[Alias.MemberOrder.ID]);
            }

            #region 权限
            String curUserId = Convert.ToString(data["CurUserID"]);
			String curUserName = Convert.ToString(data["CurUserName"]);
			if (String.IsNullOrEmpty(curUserId))
			{
				Dictionary<string, string> user = Manager.User;
				if (user == null)
				{
					Exception exp = new Exception("lang_no_right");
					throw exp;
				}
				curUserId = user["ID"];
				curUserName = user["Name"];
			}
			#endregion

			decimal sum = Convert.ToDecimal(order[Alias.MemberOrder.Sum]);
			decimal amount = 0;
			if (data.ContainsKey("Amount"))
				amount = Convert.ToDecimal(data["Amount"]);
			else
				amount = sum;

			#region 设置状态
			Dictionary<string, object> changes = new Dictionary<string, object>();
			changes[Alias.MemberOrder.RefundTime] = data["RefundTime"];
			changes[Alias.MemberOrder.RefundMemo] = data["RefundMemo"];
			changes[Alias.MemberOrder.RefundAmount] = amount;
			changes[Alias.MemberOrder.RefundOperatorID] = new Guid(curUserId);
			changes[Alias.MemberOrder.RefundOperatorName] = curUserName;
			if (amount == sum)
				changes[Alias.MemberOrder.IsPayed] = 4;
			else
				changes[Alias.MemberOrder.IsPayed] = 3;

			Dal.Modify(id, changes);
            #endregion

            //退款后处理
            OnAfterRefund(order);
        }
        public void Deliver(int id, Dictionary<string, object> data)
		{
            Dictionary<string, object> order = Dal.Get(id);
            if (CheckRight)
            {
                ValidateRight("Deliver", (Guid)order[Alias.MemberOrder.ID]);
            }

            #region 权限
            String curUserId = Convert.ToString(data["CurUserID"]);
			String curUserName = Convert.ToString(data["CurUserName"]);
			if (String.IsNullOrEmpty(curUserId))
			{
				Dictionary<string, string> user = Manager.User;
				if (user == null)
				{
					Exception exp = new Exception("lang_no_right");
					throw exp;
				}
				curUserId = user["ID"];
				curUserName = user["Name"];
			}
			#endregion

			#region 设置状态
			Dictionary<string, object> changes = new Dictionary<string, object>();
			changes[Alias.MemberOrder.DeliverTime] = data[Alias.MemberOrder.DeliverTime];
			if (data.ContainsKey(Alias.MemberOrder.DeliverMemo))
				changes[Alias.MemberOrder.DeliverMemo] = data[Alias.MemberOrder.DeliverMemo];
			changes[Alias.MemberOrder.IsDelivered] = 2;

			int amount = Convert.ToInt32(order[Alias.MemberOrder.TimeAmount]);
			DateTime deliverTime = (DateTime)data[Alias.MemberOrder.DeliverTime];
			switch (order[Alias.MemberOrder.TimeUnit].ToString())
			{
				case "MONTH":
					changes[Alias.MemberOrder.ExpiredTime] = deliverTime.AddMonths(amount);
					break;
				case "SEASON":
					changes[Alias.MemberOrder.ExpiredTime] = deliverTime.AddMonths(3 * amount);
					break;
				case "HAFE_YEAR":
					changes[Alias.MemberOrder.ExpiredTime] = deliverTime.AddMonths(6 * amount);
					break;
				case "YEAR":
					changes[Alias.MemberOrder.ExpiredTime] = deliverTime.AddYears(amount);
					break;
			}

			changes[Alias.MemberOrder.DeliverOperatorID] = new Guid(curUserId);
			changes[Alias.MemberOrder.DeliverOperatorName] = curUserName;

			Dal.Modify(id, changes);
            #endregion

            //发货后处理
            order[Alias.MemberOrder.ExpiredTime] = changes[Alias.MemberOrder.ExpiredTime];
            OnAfterDeliver(order);
        }
        public void Return(int id, Dictionary<string, object> data)
		{
            Dictionary<string, object> order = Dal.Get(id);
            if (CheckRight)
            {
                ValidateRight("Deliver", (Guid)order[Alias.MemberOrder.ID]);
            }

            #region 权限
            String curUserId = Convert.ToString(data["CurUserID"]);
			String curUserName = Convert.ToString(data["CurUserName"]);
			if (String.IsNullOrEmpty(curUserId))
			{
				Dictionary<string, string> user = Manager.User;
				if (user == null)
				{
					Exception exp = new Exception("lang_no_right");
					throw exp;
				}
				curUserId = user["ID"];
				curUserName = user["Name"];
			}
			#endregion

			#region 设置状态
			Dictionary<string, object> changes = new Dictionary<string, object>();
			changes[Alias.MemberOrder.IsDelivered] = 3;
			changes[Alias.MemberOrder.ReturnTime] = data[Alias.MemberOrder.ReturnTime];
			changes[Alias.MemberOrder.ReturnMemo] = data[Alias.MemberOrder.ReturnMemo];
			changes[Alias.MemberOrder.ReturnOperatorID] = new Guid(curUserId);
			changes[Alias.MemberOrder.ReturnOperatorName] = curUserName;

			Dal.Modify(id, changes);
            #endregion

            //退货后处理
            OnAfterReturn(order);
        }
        public void Finish(int id)
		{
			/*暂时屏蔽。有时间了，再处理权限
			if (CheckRight)
			{
				Guid guid = Dal.GetGuidFromInnerID(id);
				ValidateRight("Finish", guid);
			}
			*/

			Dictionary<string, object> changes = new Dictionary<string, object>();
			changes[Alias.MemberOrder.IsFinished] = true;
			Dal.Modify(id, changes);
		}
		public void Cancel(int id)
		{
			/*暂时屏蔽。有时间了，再处理权限
			if (CheckRight)
			{
				Guid guid = Dal.GetGuidFromInnerID(id);
				ValidateRight("Cancel", guid);
			}
			*/

			Dictionary<string, object> changes = new Dictionary<string, object>();
			changes[Alias.MemberOrder.IsCanceled] = true;

			Dal.Modify(id, changes);
		}
		public void Archive(int id)
		{
			/*暂时屏蔽。有时间了，再处理权限
			if (CheckRight)
			{
				Guid guid = Dal.GetGuidFromInnerID(id);
				ValidateRight("Archive", guid);
			}
			*/

			Dictionary<string, object> changes = new Dictionary<string, object>();
			changes[Alias.MemberOrder.IsArchived] = true;

			Dal.Modify(id, changes);
		}

        /*
		** 作用：构造跳转表单。 
		** 注释：（1）用户要登录状态。
		**		 （2）以post方式提交数据。
		**		 （3）必须提交的数据：Title，PaymentID，Amount，ReturnUrl
		**		 （4）支付宝网银接口还需提交：DefaultBank
		**/
        public object OnlinePayRequest(Guid orderId)
        {
            HttpRequest request = HttpContext.Current.Request;
            String userId = request.Form["UserID"];
            if (String.IsNullOrEmpty(userId))
            {
                Dictionary<string, string> user = Manager.User;
                if (user == null)
                    return null;

                userId = user["ID"];
            }

            #region 必须设置RechargeNotifyUrl
            Dictionary<string, string> instanceConfig = null;
            using (IInstanceConfig bll = (IInstanceConfig)Manager.CreateObject("InstanceConfig", InstanceID, Lang, false))
            {
                instanceConfig = bll.GetBasicSettings();
            }

            string notifyUrl = instanceConfig[Alias.InstanceConfig.MemberOnlinePayNotifyUrl].ToString();
            if (String.IsNullOrEmpty(notifyUrl))
                return null;
            #endregion

            #region 获取支付方式
            Dictionary<string, object> payment = null;
            using (SystemModule.IPayment paymentBll = (SystemModule.IPayment)Manager.CreateObject("Payment", 0, Lang, false))
            {
                payment = paymentBll.Get(new Guid(request.Form["PaymentID"]));
            }
            #endregion

            #region 只允许在线支付
            if (!Convert.ToBoolean(payment[SystemModule.Alias.Payment.IsOnline]))
                return null;
            #endregion

            #region 修改订单支付信息
            Guid outTradeNo = orderId;

            Dictionary<string, object> changes = new Dictionary<string, object>();
            changes[Alias.MemberOrder.PaymentID] = new Guid(request.Form["PaymentID"]);
            changes[Alias.MemberOrder.PaymentName] = payment[SystemModule.Alias.Payment.Name];
            changes[Alias.MemberOrder.PaymentType] = payment[SystemModule.Alias.Payment.Type];
            changes[Alias.MemberOrder.PaymentAccountName] = payment[SystemModule.Alias.Payment.AccountName];
            if (payment[SystemModule.Alias.Payment.Type].ToString().Contains("WEIXIN"))
                changes[Alias.MemberOrder.PaymentAccountNo] = payment[SystemModule.Alias.Payment.PartnerID];
            else
                changes[Alias.MemberOrder.PaymentAccountNo] = payment[SystemModule.Alias.Payment.Account];
            Dal.CheckRight = false;
            Dal.Modify(GetInnerIDFromGuid(orderId), changes);
            #endregion

            string type = payment[SystemModule.Alias.Payment.Type].ToString();
            string action = String.Empty;
            string method = String.Empty;
            SortedDictionary<string, string> array = new SortedDictionary<string, string>();
            if (type == "CHINA_BANK")//网银在线
            {
                action = "https://pay3.chinabank.com.cn/PayGate";
                method = "post";

                #region v_md5info
                string text = request["Amount"] + "CNY" + outTradeNo + payment[SystemModule.Alias.Payment.PartnerID] + request["ReturnUrl"] + payment[SystemModule.Alias.Payment.Key]; // 拼凑加密串
                string md5info = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(text, "md5").ToUpper();
                #endregion

                #region 构造参数
                array["v_md5info"] = md5info;
                array["v_mid"] = payment[SystemModule.Alias.Payment.PartnerID].ToString();
                array["v_oid"] = outTradeNo.ToString();
                array["v_amount"] = request["Amount"];
                array["v_moneytype"] = "CNY";
                array["v_url"] = request["ReturnUrl"].ToString();
                array["remark1"] = request["remark1"];
                array["remark2"] = "[url:=" + notifyUrl + "]";
                array["v_rcvname"] = request["v_rcvname"];
                array["v_rcvaddr"] = request["v_rcvaddr"];
                array["v_rcvtel"] = request["v_rcvtel"];
                array["v_rcvpost"] = request["v_rcvpost"];
                array["v_rcvemail"] = request["v_rcvemail"];
                array["v_rcvmobile"] = request["v_rcvmobile"];
                array["v_ordername"] = request["v_ordername"];
                array["v_orderaddr"] = request["v_orderaddr"];
                array["v_ordertel"] = request["v_ordertel"];
                array["v_orderpost"] = request["v_orderpost"];
                array["v_orderemail"] = request["v_orderemail"];
                array["v_ordermobile"] = request["v_ordermobile"];
                #endregion
            }
            else if (type == "WEIXIN_PAY_BY_WAP")//微信支付（网页接口）
            {
                action = request["ReturnUrl"];
                method = "get";

                #region 构造参数
                array["ID"] = outTradeNo.ToString();
                array["Title"] = request.Form["Title"];
                array["PaymentType"] = payment[SystemModule.Alias.Payment.Type].ToString();
                array["PaymentID"] = request.Form["PaymentID"];
                array["Amount"] = request.Form["Amount"];
                array["NotifyUrl"] = notifyUrl;
                #endregion
            }
            else if (type == "WEIXIN_PAY_BY_APP")
            {
                #region 准备配置
                Dictionary<string, string> config = new Dictionary<string, string>();
                config["APPID"] = payment[SystemModule.Alias.Payment.AccountName].ToString();
                config["MCHID"] = payment[SystemModule.Alias.Payment.PartnerID].ToString();
                config["KEY"] = payment[SystemModule.Alias.Payment.Key].ToString();
                config["APPSECRET"] = payment[SystemModule.Alias.Payment.Account].ToString();
                #endregion

                #region 准备数据
                WxPayApi.PayData data = new WxPayApi.PayData(config);
                data.SetValue("appid", config["APPID"]);
                data.SetValue("mch_id", config["MCHID"]);
                data.SetValue("device_info", "WEB");
                data.SetValue("nonce_str", Guid.NewGuid().ToString().Replace("-", ""));
                data.SetValue("body", outTradeNo.ToString());
                data.SetValue("out_trade_no", outTradeNo.ToString().Replace("-", ""));
                data.SetValue("total_fee", Convert.ToString(Convert.ToInt32(Convert.ToDecimal(request.Form["Amount"]) * 100)));
                data.SetValue("spbill_create_ip", request.UserHostAddress);
                data.SetValue("notify_url", notifyUrl);
                data.SetValue("trade_type", "APP");
                data.SetValue("sign", data.MakeSign());
                #endregion

                #region 请求Url
                String url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                req.Method = "POST";
                req.Timeout = 15 * 1000;
                req.ContentType = "text/xml";
                byte[] buffer = System.Text.Encoding.UTF8.GetBytes(data.ToXml());
                req.ContentLength = buffer.Length;
                #endregion

                #region 往服务器写入数据
                Stream reqStream = req.GetRequestStream();
                reqStream.Write(buffer, 0, buffer.Length);
                reqStream.Close();
                #endregion

                #region 获取服务端返回
                HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
                StreamReader sr = new StreamReader(resp.GetResponseStream(), Encoding.UTF8);
                String orderResult = sr.ReadToEnd().Trim();
                sr.Close();

                //统一订单数据
                data.Clear();
                data.FromXml(orderResult);
                String returnCode = Convert.ToString(data.GetValue("return_code"));
                String prepayId = Convert.ToString(data.GetValue("prepay_id"));

                //生成支付参数
                if (returnCode == "SUCCESS")
                {
                    data.Clear();
                    data.SetValue("appid", config["APPID"]);
                    data.SetValue("partnerid", config["MCHID"]);
                    data.SetValue("prepayid", prepayId);
                    data.SetValue("package", "Sign=WXPay");
                    data.SetValue("noncestr", Guid.NewGuid().ToString().Replace("-", ""));
                    data.SetValue("timestamp", WxPayApi.PrepareParam.GenerateTimeStamp());
                    data.SetValue("sign", data.MakeSign());

                    return new Dictionary<string, object>(data.GetValues());
                }
                else
                {
                    Manager.Log("EssayModule.Bll.Order - OnlinePayRequest - 生成支付参数", orderResult, Lang);
                    /*
					File.AppendAllText(Manager.MapPath("~/log.txt"), @"\r\n==========================  微信支付  =================================\r\n
																	日期：" + DateTime.Now + "\r\n" + orderResult +
																	 "\r\n=======================================================================\r\n");
					*/
                    return null;
                }
                #endregion
            }
            else if (type == "ALIPAY_DIRECT_PAY_BY_APP")
            {
                Dictionary<String, String> orderMap = new Dictionary<string, string>();
                orderMap["app_id"] = payment[SystemModule.Alias.Payment.PartnerID].ToString();
                orderMap["biz_content"] = "{" +
                                                "\"subject\":\"" + request.Form["Title"] + "\"" +
                                                ",\"seller_id\":\"\"" +
                                                ",\"total_amount\":\"" + request.Form["Amount"] + "\"" +
                                                ",\"product_code\":\"QUICK_MSECURITY_PAY\"" +
                                                ",\"out_trade_no\":\"" + outTradeNo + "\"" +
                                            "}";
                orderMap["charset"] = "utf-8";
                orderMap["method"] = "alipay.trade.app.pay";
                orderMap["notify_url"] = notifyUrl;
                orderMap["sign_type"] = "RSA";
                orderMap["timestamp"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                orderMap["version"] = "1.0";

                //
                String orderString = "";
                String orderStringEncoded = "";
                foreach (KeyValuePair<String, String> kvp in orderMap)
                {
                    if (orderString != "")
                    {
                        orderString += "&";
                        orderStringEncoded += "&";
                    }
                    orderString += kvp.Key + "=" + kvp.Value;
                    orderStringEncoded += kvp.Key + "=" + HttpUtility.UrlEncode(kvp.Value);
                }

                //签名
                String sign = HttpUtility.UrlEncodeUnicode(AliPayApi.RSA.sign(orderString, payment[SystemModule.Alias.Payment.Key].ToString(), "utf-8"));

                //
                orderStringEncoded += "&sign=" + sign;
                return orderStringEncoded;

                /*
				String orderString = "service=\"mobile.securitypay.pay\"";
				orderString += "&partner=\"" + payment[partnerIdField] + "\"";
				orderString += "&_input_charset=\"utf-8\"";
				orderString += "&notify_url=\"" + notifyUrl + "\"";
				orderString += "&out_trade_no=\"" + outTradeNo + "\"";
				orderString += "&subject=\"" + request.Form["Title"] + "\"";
				orderString += "&payment_type=\"1\"";
				orderString += "&seller_id=\"" + payment[partnerIdField] + "\"";
				orderString += "&total_fee=\"" + request.Form["Amount"] + "\"";
				orderString += "&body=\"" + request.Form["Title"] + "\"";
				//orderString += "&sign=\"" + HttpUtility.UrlEncodeUnicode(AliPayApi.RSAFromPkcs8.sign(orderString, payment[keyField].ToString(), "utf-8")) + "\"";
				orderString += "&sign=\"" + HttpUtility.UrlEncodeUnicode(AliPayApi.RSA.sign(orderString, payment[keyField].ToString(), "utf-8")) + "\"";
				orderString += "&sign_type=\"RSA\"";

				return orderString;
				*/
            }
            else//默认为支付宝
            {
                AliPayApi.AliPayApi aliPayApi = new AliPayApi.AliPayApi();

                string charset = "utf-8";
                string signType = "MD5";
                action = "https://mapi.alipay.com/gateway.do?_input_charset=" + charset;
                method = "get";

                #region 构造参数
                if (type == "ALIPAY_DIRECT_PAY_BY_WAP")
                {
                    array["partner"] = payment[SystemModule.Alias.Payment.PartnerID].ToString();
                    array["seller_id"] = payment[SystemModule.Alias.Payment.PartnerID].ToString();
                    array["_input_charset"] = charset;
                    array["service"] = "alipay.wap.create.direct.pay.by.user";
                    array["payment_type"] = "1";
                    array["notify_url"] = notifyUrl;
                    array["return_url"] = request.Form["ReturnUrl"];
                    array["out_trade_no"] = outTradeNo.ToString();
                    array["subject"] = request.Form["Title"];
                    array["total_fee"] = request.Form["Amount"];
                    array["show_url"] = HttpUtility.UrlEncode(request.Url.ToString());
                    array["sign"] = aliPayApi.BuildMysign(array, payment[SystemModule.Alias.Payment.Key].ToString(), signType, charset);
                    array["sign_type"] = signType;
                }
                else if (type == "ALIPAY_DIRECT_PAY_BY_BANK")
                {
                    array["service"] = "create_direct_pay_by_user";
                    array["paymethod"] = "bankPay";
                    array["defaultbank"] = request.Form["DefaultBank"];
                    array["partner"] = payment[SystemModule.Alias.Payment.PartnerID].ToString();
                    array["key"] = payment[SystemModule.Alias.Payment.Key].ToString();
                    array["seller_email"] = payment[SystemModule.Alias.Payment.Account].ToString();
                    array["return_url"] = request.Form["ReturnUrl"];
                    array["notify_url"] = notifyUrl;
                    array["_input_charset"] = charset;
                    array["subject"] = request.Form["Title"];
                    array["price"] = request.Form["Amount"];
                    array["body"] = request.Form["Title"];
                    array["out_trade_no"] = outTradeNo.ToString();
                    array["quantity"] = "1";
                    array["payment_type"] = "1";
                    array["logistics_fee"] = "0";
                    array["logistics_payment"] = "SELLER_PAY";
                    array["logistics_type"] = "EXPRESS";
                    array["sign"] = aliPayApi.BuildMysign(array, payment[SystemModule.Alias.Payment.Key].ToString(), signType, charset);
                    array["sign_type"] = signType;
                }
                else// if (type == "ALIPAY_DIRECT_PAY_BY_PC")
                {
                    array["service"] = "create_direct_pay_by_user";
                    array["partner"] = payment[SystemModule.Alias.Payment.PartnerID].ToString();
                    array["key"] = payment[SystemModule.Alias.Payment.Key].ToString();
                    array["seller_email"] = payment[SystemModule.Alias.Payment.Account].ToString();
                    array["return_url"] = request.Form["ReturnUrl"];
                    array["notify_url"] = notifyUrl;
                    array["_input_charset"] = charset;
                    array["subject"] = request.Form["Title"];
                    array["price"] = request.Form["Amount"];
                    array["body"] = request.Form["Title"];
                    array["out_trade_no"] = outTradeNo.ToString();
                    array["quantity"] = "1";
                    array["payment_type"] = "1";
                    array["logistics_fee"] = "0";
                    array["logistics_payment"] = "SELLER_PAY";
                    array["logistics_type"] = "EXPRESS";
                    array["sign"] = aliPayApi.BuildMysign(array, payment[SystemModule.Alias.Payment.Key].ToString(), signType, charset);
                    array["sign_type"] = signType;
                }
                #endregion
            }

            #region 表单
            StringBuilder result = new StringBuilder();
            result.Append("<form action=\"" + action + "\" method=\"" + method + "\">");
            foreach (KeyValuePair<string, string> param in array)
            {
                result.Append("<input type=\"hidden\" name=\"" + param.Key + "\" value=\"" + param.Value + "\">");
            }
            result.Append("</form>");
            return result.ToString();
            #endregion
        }
        private string OnlinePayNotify()
        {
            HttpRequest request = HttpContext.Current.Request;
            if (!String.IsNullOrEmpty(request["v_md5str"]))//网银在线
            {
                #region 获取并检查有没有参数
                string v_oid = request["v_oid"];
                string v_pstatus = request["v_pstatus"];
                string v_pstring = request["v_pstring"];
                string v_pmode = request["v_pmode"];
                string v_md5str = request["v_md5str"];
                string v_amount = request["v_amount"];
                string v_moneytype = request["v_moneytype"];
                string remark1 = request["remark1"];
                string remark2 = request["remark2"];
                #endregion

                #region 获取资金
                Dal.CheckRight = false;
                Dictionary<string, object> order = Dal.Get(new Guid(v_oid));

                if (order == null)
                {
                    #region 调试
                    //File.AppendAllText(logFile, "\r\nNo record!");
                    #endregion

                    return "error";
                }
                #endregion

                #region 获取支付方式
                Dictionary<string, object> payment = null;
                using (SystemModule.IPayment paymentBll = (SystemModule.IPayment)Manager.CreateObject("Payment", 0, Lang, false))
                {
                    payment = paymentBll.Get((Guid)order[Alias.MemberOrder.PaymentID]);
                }

                if (payment == null)
                {
                    #region 调试
                    //File.AppendAllText(logFile, "\r\nNo payment!");
                    #endregion

                    return "error";
                }
                #endregion

                #region 检查是否合法
                string str = v_oid + v_pstatus + v_amount + v_moneytype + payment[SystemModule.Alias.Payment.Key].ToString();
                str = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "md5").ToUpper();
                if (str != v_md5str)
                    return "error";
                #endregion

                #region 如果成功，修改状态
                if (v_pstatus.Equals("20"))
                {
                    OnlinePay(order, "", Convert.ToDecimal(v_amount));
                }

                return "ok";
                #endregion
            }
            else if (!String.IsNullOrEmpty(request["trade_status"]))//支付宝
            {
                AliPayApi.AliPayApi aliPayApi = new AliPayApi.AliPayApi();

                #region 获取并检查有没有参数
                SortedDictionary<string, string> array = aliPayApi.GetHttpString();
                array.Remove("Operation");
                array.Remove("Lang");
                if (array.Count == 0)
                {
                    #region 调试
                    //File.AppendAllText(logFile, "\r\nParameter error!");
                    #endregion

                    return "Parameter error!";
                }
                #endregion

                #region 获取资金
                Dal.CheckRight = false;
                Dictionary<string, object> order = Dal.Get(new Guid(array["out_trade_no"]));

                if (order == null)
                {
                    #region 调试
                    //File.AppendAllText(logFile, "\r\nNo record!");
                    #endregion

                    return "No record!";
                }
                #endregion

                #region 获取支付方式
                Dictionary<string, object> payment = null;
                using (SystemModule.IPayment paymentBll = (SystemModule.IPayment)Manager.CreateObject("Payment", 0, Lang, false))
                {
                    payment = paymentBll.Get((Guid)order[Alias.MemberOrder.PaymentID]);
                }

                if (payment == null)
                {
                    #region 调试
                    //File.AppendAllText(logFile, "\r\nNo payment!");
                    #endregion

                    return "No payment!";
                }
                #endregion

                if (payment[SystemModule.Alias.Payment.Type].ToString() == "ALIPAY_DIRECT_PAY_BY_APP")//app支付
                {
                    #region 检查是否合法
                    Dictionary<string, string> config = new Dictionary<string, string>();
                    config["PublicKey"] = payment[SystemModule.Alias.Payment.AliPayPublicKey].ToString();
                    config["SignType"] = array["sign_type"];
                    config["Charset"] = "utf-8";

                    bool isLegal = aliPayApi.GetSignVeryfy(config, array, array["sign"]);
                    if (!isLegal)
                    {
                        #region 调试
                        //File.AppendAllText(Manager.MapPath("/log.txt"), "\r\nVerify fail!");
                        #endregion

                        return "Verify fail!";
                    }
                    #endregion
                }
                else
                {
                    #region 检查是否合法
                    Dictionary<string, string> config = new Dictionary<string, string>();
                    config["Key"] = payment[SystemModule.Alias.Payment.Key].ToString();
                    config["Partner"] = payment[SystemModule.Alias.Payment.PartnerID].ToString();
                    config["PublicKey"] = payment[SystemModule.Alias.Payment.AliPayPublicKey].ToString();
                    config["SignType"] = array["sign_type"];
                    config["Charset"] = "utf-8";

                    bool isLegal = aliPayApi.Verify(config, array, array["notify_id"], array["sign"]);
                    if (!isLegal)
                    {
                        #region 调试
                        //File.AppendAllText(logFile, "\r\nVerify fail!");
                        #endregion

                        return "Verify fail!";
                    }
                    #endregion
                }

                #region 如果成功，修改状态
                if (array["trade_status"] == "TRADE_FINISHED" || array["trade_status"] == "TRADE_SUCCESS")
                {
                    OnlinePay(order, array["trade_no"], Convert.ToDecimal(array["price"]));
                }

                /*
				#region 如果用了担保交易，并且当前状态为“等待发货”，则发货
				if (array["trade_status"] == "WAIT_SELLER_SEND_GOODS")
				{
					//TODO：要做什么，暂时不清楚
				}
				#endregion
				*/

                return "success";
                #endregion
            }
            else//默认认为是微信支付
            {
                WxPayApi.Notify notify = new WxPayApi.Notify();

                try
                {
                    //获取数据
                    SortedDictionary<string, object> array = notify.GetNotifyData();

                    if (array["return_code"].ToString() == "FAIL")
                    {
                        //TODO：删除记录

                        //返回已处理
                        Manager.Log("CourseModule.Bll.MemberOrder - OnlinePayNotify - 默认认为是微信支付 - 1", "通知支付失败：" + array["return_msg"], Lang);
                        //File.AppendAllText(Manager.MapPath("/log.txt"), "\r\n\r\n=============================================\r\n通知支付失败：" + array["return_msg"] + "\r\n=============================================\r\n\r\n");
                        return notify.BuildSuccess();
                    }

                    #region 获取资金
                    Dictionary<string, object> order = Dal.Get(new Guid(array["out_trade_no"].ToString()));
                    if (order == null)
                    {
                        #region 调试
                        //File.AppendAllText(logFile, "\r\nNo record!");
                        #endregion

                        throw new Exception("out_trade_no没有对应的记录！");
                    }
                    #endregion

                    #region 获取支付方式
                    Dictionary<string, object> payment = null;
                    using (SystemModule.IPayment paymentBll = (SystemModule.IPayment)Manager.CreateObject("Payment", 0, Lang, false))
                    {
                        payment = paymentBll.Get((Guid)order[Alias.MemberOrder.PaymentID]);
                    }

                    if (payment == null)
                    {
                        #region 调试
                        //File.AppendAllText(logFile, "\r\nNo payment!");
                        #endregion

                        throw new Exception("支付对象未能获取！");
                    }

                    Dictionary<string, string> config = new Dictionary<string, string>();
                    config["APPID"] = payment[SystemModule.Alias.Payment.AccountName].ToString();
                    config["MCHID"] = payment[SystemModule.Alias.Payment.PartnerID].ToString();
                    config["KEY"] = payment[SystemModule.Alias.Payment.Key].ToString();
                    config["APPSECRET"] = payment[SystemModule.Alias.Payment.Account].ToString();
                    #endregion

                    #region 验证数据
                    notify.Verify(config, array);
                    #endregion

                    #region 处理订单状态
                    OnlinePay(order, array["transaction_id"].ToString(), Convert.ToDecimal(array["total_fee"]) / 100);
                    #endregion

                    #region debug
                    /*
					string resultString = "";
					foreach (KeyValuePair<string, object> kvp in array)
					{
						if (resultString != "")
							resultString += "\r\n";
						resultString += kvp.Key + "=" + kvp.Value;
					}
					File.AppendAllText(Manager.MapPath("/log.txt"), "\r\n\r\n=============================================\r\n支付成功\r\n=============================================\r\n" + resultString + "\r\n");
					*/
                    #endregion

                    //返回成功
                    return notify.BuildSuccess();
                }
                catch (Exception exp)
                {
                    Manager.Log("CourseModule.Bll.MemberOrder - OnlinePayNotify - 默认认为是微信支付 - 2", exp.ToString(), Lang);
                    //File.AppendAllText(Manager.MapPath("/log.txt"), "\r\n\r\n=============================================\r\n" + exp.ToString() + "\r\n=============================================\r\n\r\n");
                    return notify.BuildFail(exp.Message);
                }
            }
        }
        private bool OnlinePay(Dictionary<string, object> order, String tradeNo, Decimal amount)
		{
			if (Convert.ToInt32(order[Alias.MemberOrder.IsPayed]) > 0)
				return false;

			decimal sum = Convert.ToDecimal(order[Alias.MemberOrder.Sum]);
			if (sum != amount)
			{
				Manager.Log("CourseModule - MemberOrder - OnlinePay", "金额不相符。Sum=" + sum + "，Amount=" + amount, Lang);
				return false;
			}

			DateTime now = DateTime.Now;

			Dictionary<string, object> changes = new Dictionary<string, object>();
			changes[Alias.MemberOrder.PayTime] = now;
			changes[Alias.MemberOrder.TradeNo] = tradeNo;
			changes[Alias.MemberOrder.NotifyTime] = DateTime.Now;
			changes[Alias.MemberOrder.IsPayed] = 2;
			changes[Alias.MemberOrder.DeliverTime] = now;
			changes[Alias.MemberOrder.IsDelivered] = 2;

			int timeAmount = Convert.ToInt32(order[Alias.MemberOrder.TimeAmount]);
			switch (order[Alias.MemberOrder.TimeUnit].ToString())
			{
				case "MONTH":
					changes[Alias.MemberOrder.ExpiredTime] = now.AddMonths(timeAmount);
					break;
				case "SEASON":
					changes[Alias.MemberOrder.ExpiredTime] = now.AddMonths(3 * timeAmount);
					break;
				case "HAFE_YEAR":
					changes[Alias.MemberOrder.ExpiredTime] = now.AddMonths(6 * timeAmount);
					break;
				case "YEAR":
					changes[Alias.MemberOrder.ExpiredTime] = now.AddYears(timeAmount);
					break;
			}

			Dal.CheckRight = false;
			Dal.Modify((int)order[Alias.MemberOrder.InnerID], changes);

            //支付后处理
            OnAfterPay(order);

            //发货后处理
            order[Alias.MemberOrder.ExpiredTime] = changes[Alias.MemberOrder.ExpiredTime];
            OnAfterDeliver(order);

            return true;
		}
        private void OnAfterPay(Dictionary<string, object> order)
        {
            DataRow[] rows = Manager.Instances.Select(AliCMS.SystemModule.Alias.Module.Namespace + "='AliCMS.UserModule'");
            int userInstanceId = Convert.ToInt32(rows[0][AliCMS.SystemModule.Alias.Instance.InnerID]);

            #region 如果有代理，则分提成
            if (!Convert.IsDBNull(order[Alias.MemberOrder.DistributerID]) && Convert.ToBoolean(order[Alias.MemberOrder.DistributerIsAgent]))
            {
                Decimal agentCommision = Convert.ToDecimal(order[Alias.MemberOrder.AgentCommision]);
                if (agentCommision > 0)
                {
                    using (UserModule.User.IMoney userMoneyBll = (UserModule.User.IMoney)Manager.CreateObject("User.Money", userInstanceId, Lang, false))
                    {
                        rows = Manager.Instances.Select(SystemModule.Alias.Instance.InnerID + "=" + InstanceID);
                        object instanceId = rows[0][SystemModule.Alias.Instance.ID];

                        Dictionary<string, object> userMoney = new Dictionary<string, object>();
                        userMoney[UserModule.Alias.User.Money.UserID] = order[Alias.MemberOrder.DistributerID];
                        userMoney[UserModule.Alias.User.Money.Title] = Lang == "UYG" ? "ئەزا بولۇش - ۋاكالەتچى پايدىسى" : "开通会员 - 代理佣金";
                        userMoney[UserModule.Alias.User.Money.Amount] = agentCommision;
                        userMoney[UserModule.Alias.User.Money.Time] = DateTime.Now;
                        userMoney[UserModule.Alias.User.Money.Type] = "ALICOURSE_MEMBER_ORDER_BUY_AGENT_COMMISION";
                        userMoney[UserModule.Alias.User.Money.OrderID] = order[Alias.MemberOrder.ID];
                        userMoney[UserModule.Alias.User.Money.OrderNo] = order[Alias.MemberOrder.InnerID];
                        userMoney[UserModule.Alias.User.Money.OrderInstanceID] = instanceId;
                        userMoneyBll.Add(userMoney);
                    }

                    #region 通过公众号通知
                    #region 接收者的OpenID
                    string toUser;
                    Dictionary<string, object> user;
                    using (UserModule.IUser bll = (UserModule.IUser)Manager.CreateObject("User", userInstanceId, Lang, false))
                    {
                        user = bll.Get(order[Alias.MemberOrder.DistributerID]);
                        if (user == null)
                        {
                            Manager.Log("CourseModule.Bll.MemberOrder - OnAfterPay - 获取通知接收者的OpenID - 1", "msg：接收者没有找到\r\nuserId：" + order[Alias.MemberOrder.DistributerID], Lang);
                            return;
                        }
                        toUser = user[AliCMS.UserModule.Alias.User.WxppOpenID].ToString();

                        if (String.IsNullOrEmpty(toUser))
                        {
                            Manager.Log("CourseModule.Bll.MemberOrder - OnAfterPay - 获取通知接收者的OpenID - 2", "msg：接收者没有绑定微信\r\nuserName：" + user[AliCMS.UserModule.Alias.User.Name] + "\r\nuserId：" + order[Alias.MemberOrder.DistributerID], Lang);
                            return;
                        }
                    }
                    #endregion

                    #region 发送消息
                    StringBuilder msg = new StringBuilder();
                    msg.Append("{");
                    msg.Append("\"touser\":\"" + toUser + "\",");
                    msg.Append("\"template_id\":\"" + _templateId + "\",");
                    msg.Append("\"url\":\"" + Manager.Site[AliCMS.SystemModule.Alias.InstanceConfig.Domain] + "\",");
                    msg.Append("\"data\":");
                    msg.Append("{");
                    msg.Append("\"thing4\":{\"value\":\"" + (Lang == "UYG" ? "ئەزا بولۇش" : "开通会员") + "\"},");
                    msg.Append("\"amount5\":{\"value\":\"" + order[Alias.MemberOrder.Sum] + "\"},");
                    msg.Append("\"thing8\":{\"value\":\"" + agentCommision + "\"}");
                    msg.Append("}");
                    msg.Append("}");
                    SendWxppTemplateMsg(msg.ToString());
                    #endregion

                    #endregion
                }
            }
            #endregion

            #region 通过公众号发送“付款通知”
            /*TODO
            int alibazaInstanceId = (int)Manager.Instances.Select(AliCMS.SystemModule.Alias.Module.Namespace + "='AliCMS.AlibazaModule'")[0][AliCMS.SystemModule.Alias.Instance.InnerID];
            using (IObject bll = (IObject)Manager.CreateObject("Notification", alibazaInstanceId, Lang, false))
            {
                bll.GetType().InvokeMember("Notify", BindingFlags.InvokeMethod, null, bll, new object[] { "NT_ALICOURSE_MEMBER_ORDER_PAY", Manager.BuildJson(order) });
            }
            */
            #endregion
        }
        private void OnAfterDeliver(Dictionary<string, object> order)
        {
            #region 添加或更新会员
            using (IMember bll = (IMember)Manager.CreateObject("Member", InstanceID, Lang, false))
            {
                DataTable memberTable = bll.List(1, 1, Alias.Member.UserID + "=" + order[Alias.MemberOrder.UserID], null);
                if (memberTable.Rows.Count == 0)
                {
                    Dictionary<string, object> item = new Dictionary<string, object>();
                    item[Alias.Member.LevelID] = order[Alias.MemberOrder.LevelID];
                    item[Alias.Member.UserID] = order[Alias.MemberOrder.UserID];
                    item[Alias.Member.UserName] = order[Alias.MemberOrder.UserName];
                    item[Alias.Member.UserNickname] = order[Alias.MemberOrder.UserNickname];
                    item[Alias.Member.UserHead] = order[Alias.MemberOrder.UserHead];
            
                    DataRow[] rows = Manager.Instances.Select(AliCMS.SystemModule.Alias.Module.Namespace + "='AliCMS.UserModule'");
                    int userInstanceId = Convert.ToInt32(rows[0][AliCMS.SystemModule.Alias.Instance.InnerID]);
                    using (UserModule.IUser userBll = (UserModule.IUser)Manager.CreateObject("User", userInstanceId, Lang, false))
                    {
                        Dictionary<string, object> user = userBll.Get(order[Alias.MemberOrder.UserID]);
                        item[Alias.Member.UserRealName] = user[UserModule.Alias.User.RealName];
                        item[Alias.Member.UserMobile] = user[UserModule.Alias.User.Mobile];
                    }

                    if (!Convert.IsDBNull(order[Alias.MemberOrder.DistributerID]) && Convert.ToBoolean(order[Alias.MemberOrder.DistributerIsAgent]))
                    {
                        item[Alias.Member.AgentID] = order[Alias.MemberOrder.DistributerID];
                        item[Alias.Member.AgentName] = order[Alias.MemberOrder.DistributerName];
                        item[Alias.Member.AgentNickname] = order[Alias.MemberOrder.DistributerNickname];
                        item[Alias.Member.AgentHead] = order[Alias.MemberOrder.DistributerHead];
                    }
                    item[Alias.Member.ExpiredTime] = order[Alias.MemberOrder.ExpiredTime];
                    item[Alias.Member.CreatorID] = order[Alias.MemberOrder.UserID];
                    item[Alias.Member.CreatorName] = order[Alias.MemberOrder.UserName];
                    bll.Add(item);
                }
                else
                {
                    Dictionary<string, object> changes = new Dictionary<string, object>();
                    changes[Alias.Member.LevelID] = order[Alias.MemberOrder.LevelID];
                    changes[Alias.Member.ExpiredTime] = order[Alias.MemberOrder.ExpiredTime];
                    changes[Alias.Member.IsDeleted] = false;
                    bll.Modify(Convert.ToInt32(memberTable.Rows[0][Alias.Member.InnerID]), changes);
                }
            }
            #endregion
        }
        private void OnAfterRefund(Dictionary<string, object> order)
        {
            DataRow[] rows = Manager.Instances.Select(AliCMS.SystemModule.Alias.Module.Namespace + "='AliCMS.UserModule'");
            int userInstanceId = Convert.ToInt32(rows[0][AliCMS.SystemModule.Alias.Instance.InnerID]);

            #region 退代理佣金
            if (!Convert.IsDBNull(order[Alias.MemberOrder.DistributerID]) && Convert.ToBoolean(order[Alias.MemberOrder.DistributerIsAgent]))
            {
                Decimal agentCommision = Convert.ToDecimal(order[Alias.MemberOrder.AgentCommision]);
                if (agentCommision > 0)
                {
                    using (UserModule.User.IMoney userMoneyBll = (UserModule.User.IMoney)Manager.CreateObject("User.Money", userInstanceId, Lang, false))
                    {
                        rows = Manager.Instances.Select(SystemModule.Alias.Instance.InnerID + "=" + InstanceID);
                        object instanceId = rows[0][SystemModule.Alias.Instance.ID];

                        Dictionary<string, object> userMoney = new Dictionary<string, object>();
                        userMoney[UserModule.Alias.User.Money.UserID] = order[Alias.MemberOrder.DistributerID];
                        userMoney[UserModule.Alias.User.Money.Title] = Lang == "UYG" ? " ئەزانى بىكار قىلىش - ۋاكالەتچى پايدىسى" : "取消会员 - 代理佣金";
                        userMoney[UserModule.Alias.User.Money.Amount] = -agentCommision;
                        userMoney[UserModule.Alias.User.Money.Time] = DateTime.Now;
                        userMoney[UserModule.Alias.User.Money.Type] = "ALICOURSE_MEMBER_ORDER_REFUND_AGENT_COMMISION";
                        userMoney[UserModule.Alias.User.Money.OrderID] = order[Alias.MemberOrder.ID];
                        userMoney[UserModule.Alias.User.Money.OrderNo] = order[Alias.MemberOrder.InnerID];
                        userMoney[UserModule.Alias.User.Money.OrderInstanceID] = instanceId;
                        userMoneyBll.Add(userMoney);
                    }
                }
            }
            #endregion
        }
        private void OnAfterReturn(Dictionary<string, object> order)
        {
            #region 删除会员
            using (IMember bll = (IMember)Manager.CreateObject("Member", InstanceID, Lang, false))
            {
                DataTable table = bll.List(-1, -1, Alias.Member.UserID + "=" + order[Alias.MemberOrder.UserID], null);
                foreach (DataRow row in table.Rows)
                {
                    bll.Delete(Convert.ToInt32(row[Alias.Member.InnerID]));
                }
            }
            #endregion
        }

        #region 统计
        public string Stat(Dictionary<string, object> data)
        {
            if (data.ContainsKey("Start"))
            {
                data["Start"] = Convert.ToDateTime(data["Start"]);
            }

            if (data.ContainsKey("End"))
            {
                data["End"] = Convert.ToDateTime(data["End"]);
            }

            return Dal.Stat(data);
        }
        public string StatHourly(Dictionary<string, object> data)
        {
            if (data.ContainsKey("Start"))
            {
                data["Start"] = Convert.ToDateTime(data["Start"]);
            }

            if (data.ContainsKey("End"))
            {
                data["End"] = Convert.ToDateTime(data["End"]);
            }

            return Dal.StatHourly(data);
        }
        public string StatDaily(Dictionary<string, object> data)
        {
            if (data.ContainsKey("Start"))
            {
                data["Start"] = Convert.ToDateTime(data["Start"]);
            }

            if (data.ContainsKey("End"))
            {
                data["End"] = Convert.ToDateTime(data["End"]);
            }

            return Dal.StatDaily(data);
        }
        public string StatMonthly(Dictionary<string, object> data)
        {
            if (data.ContainsKey("Start"))
            {
                data["Start"] = Convert.ToDateTime(data["Start"]);
            }

            if (data.ContainsKey("End"))
            {
                data["End"] = Convert.ToDateTime(data["End"]);
            }

            return Dal.StatMonthly(data);
        }
        #endregion

        #region 代理统计
        public string Agent_StatOne(Guid agentId, Dictionary<string, object> data)
        {
            if (data.ContainsKey("Start"))
            {
                data["Start"] = Convert.ToDateTime(data["Start"]);
            }

            if (data.ContainsKey("End"))
            {
                data["End"] = Convert.ToDateTime(data["End"]);
            }

            return Dal.Agent_StatOne(agentId, data);
        }
        public string Agent_StatAll(Dictionary<string, object> data)
        {
            if (data.ContainsKey("Start"))
            {
                data["Start"] = Convert.ToDateTime(data["Start"].ToString());
            }

            if (data.ContainsKey("End"))
            {
                data["End"] = Convert.ToDateTime(data["End"].ToString());
            }

            return Dal.Agent_StatAll(data);
        }
        public string Agent_StatHourly(Guid agentId, Dictionary<string, object> data)
        {
            if (data.ContainsKey("Start"))
            {
                data["Start"] = Convert.ToDateTime(data["Start"]);
            }

            if (data.ContainsKey("End"))
            {
                data["End"] = Convert.ToDateTime(data["End"]);
            }

            return Dal.Agent_StatHourly(agentId, data);
        }
        public string Agent_StatDaily(Guid agentId, Dictionary<string, object> data)
        {
            if (data.ContainsKey("Start"))
            {
                data["Start"] = Convert.ToDateTime(data["Start"]);
            }

            if (data.ContainsKey("End"))
            {
                data["End"] = Convert.ToDateTime(data["End"]);
            }

            return Dal.Agent_StatDaily(agentId, data);
        }
        public string Agent_StatMonthly(Guid agentId, Dictionary<string, object> data)
        {
            if (data.ContainsKey("Start"))
            {
                data["Start"] = Convert.ToDateTime(data["Start"]);
            }

            if (data.ContainsKey("End"))
            {
                data["End"] = Convert.ToDateTime(data["End"]);
            }

            return Dal.Agent_StatMonthly(agentId, data);
        }
        #endregion

        private void SendWxppTemplateMsg(string msg)
        {
            #region 获取AccessToken
            string appId = Manager.Site[AliCMS.SystemModule.Alias.InstanceConfig.WxppAppID + Lang];
            string appSecret = Manager.Site[AliCMS.SystemModule.Alias.InstanceConfig.WxppAppSecret + Lang];
            string accessToken = GetAccessToken(appId, appSecret);

            if (accessToken == null)
                return;
            #endregion

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken);
            request.Method = "POST";
            request.Timeout = 15 * 1000;
            request.ContentType = "application/json";
            byte[] buffer = System.Text.Encoding.UTF8.GetBytes(msg.ToString());
            request.ContentLength = buffer.Length;

            //往服务器写入数据
            Stream reqStream = request.GetRequestStream();
            reqStream.Write(buffer, 0, buffer.Length);
            reqStream.Close();

            //获取服务端返回
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
            String result = sr.ReadToEnd().Trim();
            sr.Close();

            JavaScriptSerializer serializer = new JavaScriptSerializer();
            Dictionary<string, object> json = serializer.DeserializeObject(result) as Dictionary<string, object>;
            if (Convert.ToInt32(json["errcode"]) != 0)
            {
                Manager.Log("CourseModule.Bll.Order - SendWxppTemplateMsg", "msg：模板消息发送失败\r\nerrcode：" + json["errcode"] + "\r\nerrmsg：" + json["errmsg"] + "\r\nmsg：" + msg.ToString(), Lang);
            }
        }
        public string GetAccessToken(string appId, string appSecret)
        {
            string dir = Manager.MapPath(Manager.GetDataPath(InstanceID, null)) + "access_token/";
            if (!Directory.Exists(dir))
                Directory.CreateDirectory(dir);

            int counter = 0;
            string lockFile = dir + appId + ".lock";
            while (File.Exists(lockFile))
            {
                if (counter == 5)
                {
                    if (DateTime.Now.Subtract(File.GetCreationTime(lockFile)).Minutes > 5)
                    {
                        File.Delete(lockFile);
                        break;
                    }

                    return null;
                }

                Thread.Sleep(1000);//等待一秒
                counter++;
            }

            string token = null;
            DateTime expiredTime = DateTime.MinValue;
            JavaScriptSerializer serializer = new JavaScriptSerializer();

            try
            {
                _logWriteLock.EnterWriteLock();

                //创建锁定文件
                File.Create(lockFile).Close();

                string path = dir + appId + ".txt";
                if (File.Exists(path))
                {
                    Dictionary<string, object> json = serializer.DeserializeObject(File.ReadAllText(path)) as Dictionary<string, object>;
                    token = json["token"].ToString();
                    if (json["expiredTime"].ToString() != "")
                        expiredTime = Convert.ToDateTime(json["expiredTime"].ToString());
                }

                if (String.IsNullOrEmpty(token) || expiredTime.Subtract(DateTime.Now).TotalMinutes < 5)
                {
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appSecret);
                    request.Timeout = 15 * 1000;
                    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                    StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                    String result = sr.ReadToEnd().Trim();
                    sr.Close();

                    Dictionary<string, object> json = serializer.DeserializeObject(result) as Dictionary<string, object>;
                    if (!json.ContainsKey("access_token"))
                    {
                        Manager.Log("CourseModule - GetAccessToken - get", "appId：" + appId + "\r\nResult：" + result, Lang);
                        return null;
                    }

                    token = json["access_token"].ToString();
                    expiredTime = DateTime.Now.AddSeconds(Convert.ToInt32(json["expires_in"]));
                    File.WriteAllText(path, "{\"token\":\"" + token + "\",\"expiredTime\":\"" + expiredTime.ToString() + "\"}");
                }
            }
            catch (Exception exp)
            {
                Manager.Log("CourseModule - GetAccessToken", "appId：" + appId + "\r\nException：" + exp.ToString(), Lang);
            }
            finally
            {
                File.Delete(lockFile);
                _logWriteLock.ExitWriteLock();
            }

            return token;
        }

        #region Fields
        string _result = null;
        public static ReaderWriterLockSlim _logWriteLock = new ReaderWriterLockSlim();
        public static string _templateId = "qsrPGNFuiZ4Br7NW8OpBBxFByBKjk-eLBcchshnvweQ";
        #endregion

        #region Properties
        private Dal.IMemberOrder Dal
		{
			get { return (Dal.IMemberOrder)DalBase; }
		}
		#endregion
	}
}
